﻿<CodeSnippetTabbed DocLink="https://docs.devexpress.com/Blazor/DevExpress.Blazor.DxUpload#validation">
<CodeSnippetTabPage Text="Razor">@(@"@inject NavigationManager NavigationManager

<DxUpload Name=""myFile"" UploadUrl=""@GetUploadUrl(""api/Upload/UploadImage/"")""
    AllowedFileExtensions=""@(new List<string> { "".jpg"", "".jpeg"", "".gif"", "".png"" })"" MaxFileSize=""4000000"">
</DxUpload>

@code {
    protected string GetUploadUrl(string url) {
        return NavigationManager.ToAbsoluteUri(url).AbsoluteUri;
    }
}")
</CodeSnippetTabPage>
<CodeSnippetTabPage Text="UploadController" Language="csharp">@(@"[Route(""api/[controller]"")]
public class UploadController : ControllerBase {
    private readonly IWebHostEnvironment _hostingEnvironment;

    public UploadController(IWebHostEnvironment hostingEnvironment) {
        _hostingEnvironment = hostingEnvironment;
    }

    [HttpPost(""[action]"")]
    public ActionResult UploadImage(IFormFile myFile) {
        try {
            string[] imageExtensions = { "".jpg"", "".jpeg"", "".gif"", "".png"" };

            var fileName = myFile.FileName.ToLower();
            var isValidExtenstion = imageExtensions.Any(ext => {
                return fileName.LastIndexOf(ext) > -1;
            });

            if(isValidExtenstion) {
                var path = Path.Combine(_hostingEnvironment.WebRootPath, ""uploads"");
                if(!Directory.Exists(path))
                    Directory.CreateDirectory(path);

                using(var fileStream = System.IO.File.Create(Path.Combine(path, myFile.FileName))) {
                    myFile.CopyTo(fileStream);
                }
            }
        } catch {
            Response.StatusCode = 400;
        }

        return new EmptyResult();
    }
}")
</CodeSnippetTabPage>
</CodeSnippetTabbed>
